package io.renren.modules.hos.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import io.renren.common.utils.SendMsgUtils;
import io.renren.config.AlipayConfig;
import io.renren.modules.hos.entity.AppointmentEntity;
import io.renren.modules.hos.entity.OrderEntity;
import io.renren.modules.hos.entity.PatientEntity;
import io.renren.modules.hos.form.AliPayForm;
import io.renren.modules.hos.service.AppointmentService;
import io.renren.modules.hos.service.OrderService;
import io.renren.modules.hos.service.PatientService;
import io.renren.modules.hos.service.PayService;
import io.renren.modules.hos.utils.Alipay;
import io.renren.modules.hos.utils.HosDateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class PayServiceImpl implements PayService {
    @Autowired
    private AppointmentService appointmentService;
    @Autowired
    private AlipayConfig alipayConfig;
    @Autowired
    private PatientService patientService;
    @Autowired
    private OrderService orderService;

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public String appointmentPay(AliPayForm payForm) {
        AppointmentEntity appointmentEntity = appointmentService.selectByOrderNum(payForm.getOut_trade_no());
        System.out.println(payForm.getOut_trade_no());
        System.out.println(appointmentEntity);
        //更新支付时间以及预约挂号状态
        appointmentEntity.setPayTime(new Date());
        appointmentEntity.setOrderStatus(2);
        appointmentService.updateById(appointmentEntity);

        //发送短信提示预约成功
        PatientEntity patientEntity = patientService.getById(appointmentEntity.getPatientId());
        String time = null;
        if (appointmentEntity.getReserveTime() == 0){
            time = "上午";
        }else {
          time = "下午";
        }
        String date = HosDateUtils.date(appointmentEntity.getReserveDate());
        String msg = SendMsgUtils.sendAppointmentMsg(patientEntity.getPhone(),
                patientEntity.getPatientName(),
                date, time);


        logger.info("================================================================");
        logger.info("短信发送返回提示：" + msg);

        System.out.println(patientEntity.getPhone() + patientEntity.getPatientName() + appointmentEntity.getReserveDate().toString() + time);

        return alipay(payForm);
    }

    @Override
    public String orderPay(AliPayForm payForm) {
        System.out.println(payForm.getOut_trade_no());
        OrderEntity orderEntity = orderService.selectByOrderNum(payForm.getOut_trade_no());
        //修改订单状态
        orderEntity.setPayTime(new Date());
        orderEntity.setPayStatus(1);
        orderEntity.setUpdateTime(new Date());
        orderService.updateById(orderEntity);
        System.out.println(orderEntity);

        return alipay(payForm);
    }


    private  String alipay(AliPayForm payForm){
        // 1、获得初始化的AlipayClient
        String result = null;
        String serverUrl = alipayConfig.getGatewayUrl();
        String appId = alipayConfig.getAppId();
        String privateKey = alipayConfig.getPrivateKey();
        String format = "json";
        String charset = alipayConfig.getCharset();
        String alipayPublicKey = alipayConfig.getPublicKey();
        String signType = alipayConfig.getSignType();
        String returnUrl = alipayConfig.getReturnUrl();
        String notifyUrl = alipayConfig.getNotifyUrl();
        AlipayClient alipayClient = new DefaultAlipayClient(serverUrl, appId, privateKey, format, charset, alipayPublicKey, signType);
        // 2、设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        // 页面跳转同步通知页面路径
        alipayRequest.setReturnUrl(returnUrl);
        // 服务器异步通知页面路径
        alipayRequest.setNotifyUrl(notifyUrl);
        // 封装参数
        alipayRequest.setBizContent(JSON.toJSONString(payForm));
        // 3、请求支付宝进行付款，并获取支付结果
        try {
            result = alipayClient.pageExecute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        System.out.println(result);
        // 返回付款信息
        return result;
    }
}
